package com.gongj.rabbit.produce.tx;

import com.gongj.rabbit.utils.RabbitMQUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
/*
 * 事务机制
 */
public class produce1 {

    public static void main(String[] args) throws IOException {
        Connection conn = RabbitMQUtil.createConn();
        Channel channel = conn.createChannel();
        String quequ = "queue-1";
        String exchange = "exchange-1";
        String key = "key-1";
        //创建交换机
        channel.exchangeDeclare(exchange, BuiltinExchangeType.TOPIC,true);
        //创建队列
        channel.queueDeclare(quequ,true,false,false,null);
        //队列与交换机绑定
        channel.queueBind(quequ,exchange,key);
        //开启事务
        channel.txSelect();
        for (int a = 0; a < 10; a++) {
            try{
                channel.basicPublish(exchange,"key-1",null,"发送路由key为 = key-1 的消息".getBytes());
                //int i = 1/0;
                //提交事务
                channel.txCommit();
                System.out.println("发送成功");
            }catch (Exception e){
                System.out.println("发送失败，进行日志记录");
                //回滚事务
                channel.txRollback();
            }
        }

        RabbitMQUtil.closeConn(channel,conn);
    }
}
